import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import "../views/vehicles" as VehicleViews
import "../components" as Components
import "../dialogs" as Dialogs
import "../styles" as Styles

Page {
    id: vehicleManagementScreen
    title: qsTr("车辆管理")

    // 自定义属性
    property var vehicleViewModel: null
    property var taskViewModel: null
    property var agvList: []
    property var selectedAgv: null
    property int selectedAgvIndex: -1  // 存储选中的 model index
    property string filterStatus: "all"
    property string searchText: ""
    property bool showManualControlDialog: false

    background: Rectangle {
        color: Styles.Theme.background
    }

    // 已移除样例数据，使用vehicleViewModel.agvListModel获取真实数据
    Component.onCompleted: {
        // 连接到全局ViewModel
        vehicleViewModel = GlobalVehicleViewModel
        taskViewModel = GlobalTaskViewModel

        // 数据由VehicleViewModel自动提供
        if (vehicleViewModel) {
            vehicleViewModel.refreshAgvList()
        }
    }

    Connections {
        target: vehicleViewModel

        function onAgvDataUpdated(agvNumber) {
            if (selectedAgv && selectedAgv.agvNumber === agvNumber) {
                syncSelectedAgv(agvNumber)
            }
        }
    }

    Connections {
        target: vehicleViewModel ? vehicleViewModel.agvListModel : null

        function onModelReset() {
            refreshSelectedAgv()
        }

        function onRowsRemoved(parent, first, last) {
            refreshSelectedAgv()
        }
    }

    // 主布局
    ColumnLayout {
        anchors.fill: parent
        anchors.margins: Styles.Theme.spacingNormal
        spacing: Styles.Theme.spacingNormal

        // 顶部工具栏
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 100
            color: Styles.Theme.surface
            border.color: Styles.Theme.border
            border.width: 1
            radius: Styles.Theme.radiusSmall

            RowLayout {
                anchors.fill: parent
                anchors.leftMargin: Styles.Theme.spacingNormal
                anchors.rightMargin: Styles.Theme.spacingNormal
                spacing: Styles.Theme.spacingNormal

                // 标题和状态概览
                ColumnLayout {
                    Layout.fillWidth: false
                    spacing: 2

                    Text {
                        text: qsTr("车辆管理")
                        color: Styles.Theme.textPrimary
                        font.pixelSize: Styles.Theme.fontSizeLarge
                        font.weight: Styles.Theme.fontWeightMedium
                    }

                    Text {
                        text: getVehicleStatusSummary()
                        color: Styles.Theme.textSecondary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                    }
                }

                Item { Layout.fillWidth: true }

                // 搜索框
                Components.SearchBar {
                    Layout.preferredWidth: 250
                    placeholderText: qsTr("搜索AGV ID、型号...")
                    searchText: searchText
                    onTextSearched: searchText = text
                    onSearchSubmitted: performSearch()
                }

                // 筛选器
                Components.CustomComboBox {
                    Layout.preferredWidth: 120
                    model: [
                        { text: qsTr("全部状态"), value: "all" },
                        { text: qsTr("空闲"), value: "idle" },
                        { text: qsTr("执行中"), value: "executing" },
                        { text: qsTr("充电中"), value: "charging" },
                        { text: qsTr("故障"), value: "error" },
                        { text: qsTr("离线"), value: "offline" }
                    ]
                    textRole: "text"
                    valueRole: "value"
                    onCurrentValueChanged: {
                        filterStatus = currentValue
                        applyFilter()
                    }
                }

                // 刷新按钮
                Components.ActionButton {
                    text: qsTr("刷新")
                    iconSource: "qrc:/icons/refresh.svg"
                    buttonType: "secondary"
                    onClicked: refreshVehicles()
                }
                
                // 添加AGV按钮
                Components.ActionButton {
                    text: qsTr("添加AGV")
                    iconSource: "+"
                    buttonType: "primary"
                    onClicked: addNewAgv()
                }

                // 系统控制按钮
                Components.ActionButton {
                    text: qsTr("系统设置")
                    iconSource: "⚙️"
                    buttonType: "secondary"
                    onClicked: openSystemSettings()
                }
            }
        }

        // 主内容区域
        RowLayout {
            Layout.fillWidth: true
            Layout.fillHeight: true
            spacing: Styles.Theme.spacingNormal

            // 左侧 - 车辆列表（卡片式）
            Rectangle {
                Layout.fillHeight: true
                Layout.preferredWidth: 420
                Layout.minimumWidth: 350
                Layout.maximumWidth: 500
                color: Styles.Theme.surface
                border.color: Styles.Theme.border
                border.width: 1
                radius: Styles.Theme.radiusNormal

                ColumnLayout {
                    anchors.fill: parent
                    anchors.margins: Styles.Theme.spacingSmall
                    spacing: 0

                    ScrollView {
                        id: vehicleScrollView
                        Layout.fillWidth: true
                        Layout.fillHeight: true
                        clip: true

                        ScrollBar.horizontal.policy: ScrollBar.AlwaysOff

                        ScrollBar.vertical: ScrollBar {
                            id: vbar
                            width: 8
                            policy: ScrollBar.AsNeeded
                            anchors.right: parent.right
                            anchors.top: parent.top
                            anchors.bottom: parent.bottom

                            contentItem: Rectangle {
                                implicitWidth: 8
                                radius: 4
                                color: vbar.pressed ? Styles.Theme.primary :
                                       vbar.hovered ? Styles.Theme.textSecondary :
                                       Styles.Theme.textTertiary
                                opacity: vbar.pressed ? 0.9 : vbar.hovered ? 0.7 : 0.5

                                Behavior on color { ColorAnimation { duration: 150 } }
                                Behavior on opacity { NumberAnimation { duration: 150 } }
                            }

                            background: Rectangle {
                                color: Styles.Theme.backgroundSecondary
                                opacity: 0.3
                                radius: 4
                            }
                        }

                        Column {
                            width: vehicleScrollView.width - 12  // 为右侧滚动条留出空间 (8px + 4px margin)
                            spacing: Styles.Theme.spacingNormal
                            topPadding: Styles.Theme.spacingSmall
                            bottomPadding: Styles.Theme.spacingSmall

                        Repeater {
                            model: vehicleViewModel ? vehicleViewModel.agvListModel : null

                            // AGV卡片
                            delegate: Rectangle {
                                width: parent.width
                                height: 140
                                color: selectedAgv && selectedAgv.agvNumber === model.agvNumber ? Styles.Theme.primary : Styles.Theme.backgroundSecondary
                                border.color: selectedAgv && selectedAgv.agvNumber === model.agvNumber ? Styles.Theme.primary : Styles.Theme.border
                                border.width: 1
                                radius: Styles.Theme.radiusSmall

                                // 悬停效果
                                opacity: cardMouseArea.containsMouse ? 0.95 : 1.0
                                Behavior on opacity { NumberAnimation { duration: 150 } }

                                Column {
                                    anchors.fill: parent
                                    anchors.margins: Styles.Theme.spacingNormal
                                    spacing: Styles.Theme.spacingSmall

                                    // 顶部：ID和状态
                                    Row {
                                        width: parent.width
                                        spacing: Styles.Theme.spacingSmall

                                        Text {
                                            text: model.name || ("AGV-" + model.agvNumber)
                                            color: selectedAgv && selectedAgv.agvNumber === model.agvNumber ? Styles.Theme.textOnPrimary : Styles.Theme.textPrimary
                                            font.pixelSize: Styles.Theme.fontSizeLarge
                                            font.weight: Styles.Theme.fontWeightMedium
                                            width: parent.width - statusBadge.width - parent.spacing
                                            elide: Text.ElideRight
                                        }

                                        Rectangle {
                                            id: statusBadge
                                            width: 80
                                            height: 24
                                            radius: 12
                                            color: getStatusColorFromModel(model.isOnline, model.isCharging, model.isControlled)

                                            Text {
                                                anchors.centerIn: parent
                                                text: getStatusTextFromModel(model.isOnline, model.isCharging, model.isControlled)
                                                color: Styles.Theme.textOnPrimary
                                                font.pixelSize: Styles.Theme.fontSizeSmall
                                                font.weight: Styles.Theme.fontWeightMedium
                                            }
                                        }
                                    }

                                    // 名称和类型
                                    Row {
                                        width: parent.width
                                        spacing: Styles.Theme.spacingSmall

                                        Text {
                                            text: model.name || ""
                                            color: selectedAgv && selectedAgv.agvNumber === model.agvNumber ? Styles.Theme.textOnPrimary : Styles.Theme.textSecondary
                                            font.pixelSize: Styles.Theme.fontSizeNormal
                                            elide: Text.ElideRight
                                            width: parent.width / 2 - parent.spacing
                                        }

                                        Text {
                                            text: model.ipAddress || ""
                                            color: selectedAgv && selectedAgv.agvNumber === model.agvNumber ? Styles.Theme.textOnPrimary : Styles.Theme.textSecondary
                                            font.pixelSize: Styles.Theme.fontSizeNormal
                                            elide: Text.ElideRight
                                        }
                                    }

                                    // 位置和电池
                                    Row {
                                        width: parent.width
                                        spacing: Styles.Theme.spacingLarge

                                        Row {
                                            spacing: Styles.Theme.spacingSmall

                                            Text {
                                                text: "📍"
                                                font.pixelSize: Styles.Theme.fontSizeNormal
                                            }

                                            Text {
                                                text: model.location || qsTr("未知")
                                                color: selectedAgv && selectedAgv.agvNumber === model.agvNumber ? Styles.Theme.textOnPrimary : Styles.Theme.textSecondary
                                                font.pixelSize: Styles.Theme.fontSizeNormal
                                            }
                                        }

                                        Row {
                                            spacing: Styles.Theme.spacingSmall

                                            Text {
                                                text: "🔋"
                                                font.pixelSize: Styles.Theme.fontSizeNormal
                                            }

                                            Text {
                                                text: model.batteryLevel + "%"
                                                color: selectedAgv && selectedAgv.agvNumber === model.agvNumber ? Styles.Theme.textOnPrimary : Styles.Theme.textSecondary
                                                font.pixelSize: Styles.Theme.fontSizeNormal
                                            }
                                        }
                                    }

                                    // 当前任务或错误信息
                                    Text {
                                        width: parent.width
                                        text: model.currentJob || qsTr("空闲中")
                                        color: selectedAgv && selectedAgv.agvNumber === model.agvNumber ? Styles.Theme.textOnPrimary : Styles.Theme.textTertiary
                                        font.pixelSize: Styles.Theme.fontSizeSmall
                                        elide: Text.ElideRight
                                    }
                                }

                                MouseArea {
                                    id: cardMouseArea
                                    anchors.fill: parent
                                    hoverEnabled: true
                                    cursorShape: Qt.PointingHandCursor

                                    onClicked: {
                                        syncSelectedAgv(model.agvNumber)
                                    }

                                    onDoubleClicked: {
                                        handleAgvDoubleClick(selectedAgv)
                                    }
                                }
                            }
                        }
                    }
                }
                }
            }


            // 右侧 - AGV详情和控制面板

            Rectangle {
                Layout.fillHeight: true
                Layout.fillWidth: true
                color: Styles.Theme.surface
                border.color: Styles.Theme.border
                border.width: 1
                radius: Styles.Theme.radiusNormal

                StackLayout {
                    anchors.fill: parent
                    anchors.margins: Styles.Theme.spacingNormal
                    currentIndex: selectedAgv ? 1 : 0

                    // 无选择提示
                    Item {
                        ColumnLayout {
                            anchors.centerIn: parent
                            spacing: Styles.Theme.spacingNormal

                            Text {
                                text: "🚛"
                                font.pixelSize: 64
                                Layout.alignment: Qt.AlignHCenter
                                opacity: 0.3
                            }

                            Text {
                                text: qsTr("请选择AGV")
                                color: Styles.Theme.textSecondary
                                font.pixelSize: Styles.Theme.fontSizeLarge
                                Layout.alignment: Qt.AlignHCenter
                            }

                            Text {
                                text: qsTr("从左侧列表中选择一个AGV\n查看详细信息和执行控制操作")
                                color: Styles.Theme.textSecondary
                                font.pixelSize: Styles.Theme.fontSizeNormal
                                horizontalAlignment: Text.AlignHCenter
                                Layout.alignment: Qt.AlignHCenter
                            }
                        }
                    }

                    // AGV详情和控制区域
                    ColumnLayout {
                        Layout.fillWidth: true
                        Layout.fillHeight: true
                        spacing: Styles.Theme.spacingNormal

                        // 顶部标题栏
                        RowLayout {
                            Layout.fillWidth: true

                            Text {
                                text: selectedAgv ? qsTr("AGV详情 - %1").arg(selectedAgv.id) : ""
                                color: Styles.Theme.textPrimary
                                font.pixelSize: Styles.Theme.fontSizeLarge
                                font.weight: Styles.Theme.fontWeightMedium
                                Layout.fillWidth: true
                            }

                            Components.ActionButton {
                                size: "small"
                                text: qsTr("维护模式")
                                iconSource: "🔧"
                                buttonType: selectedAgv && selectedAgv.maintenanceMode ? "danger" : "secondary"
                                enabled: selectedAgv && selectedAgv.status !== "offline"
                                onClicked: toggleMaintenanceMode(selectedAgv)
                            }
                        }

                        // 主内容区域
                        RowLayout {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            spacing: Styles.Theme.spacingNormal

                            // 左侧 - AGV详情
                            VehicleViews.VehicleDetailsView {
                                Layout.fillHeight: true
                                Layout.preferredWidth: 450
                                Layout.minimumWidth: 420

                                agv: selectedAgv

                                onAgvModified: function(agv) {
                                    handleAgvModified(agv)
                                }
                            }

                            // 右侧 - 控制面板
                            VehicleViews.VehicleControlView {
                                Layout.fillHeight: true
                                Layout.fillWidth: true

                                agv: selectedAgv
                                vehicleViewModel: vehicleManagementScreen.vehicleViewModel
                                taskViewModel: vehicleManagementScreen.taskViewModel
                            }
                        }
                    }
                }
            }

        }
        // 底部状态栏

        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 30
            color: Styles.Theme.surface
            border.color: Styles.Theme.border
            border.width: 1
            radius: Styles.Theme.radiusSmall

            RowLayout {
                anchors.fill: parent
                anchors.leftMargin: Styles.Theme.spacingNormal
                anchors.rightMargin: Styles.Theme.spacingNormal

                Text {
                    text: getDetailedStatusText()
                    color: Styles.Theme.textSecondary
                    font.pixelSize: Styles.Theme.fontSizeSmall
                    Layout.fillWidth: true
                }

                Text {
                    text: qsTr("最后更新: %1").arg(formatCurrentTime())
                    color: Styles.Theme.textSecondary
                    font.pixelSize: Styles.Theme.fontSizeSmall
                }
            }
        }

    }

    // 手动控制对话框
    Dialogs.ManualControlDialog {
        id: manualControlDialog
        visible: showManualControlDialog
        agv: selectedAgv
        onAccepted: function(commands) {
            executeManualControl(selectedAgv, commands)
            showManualControlDialog = false
        }
        onRejected: {
            showManualControlDialog = false
        }
    }

    // 确认对话框
    Components.ConfirmDialog {
        id: confirmDialog

        onAccepted: {
            if (callback) callback()
        }
    }

    // 事件处理函数
    function performSearch() {
        if (vehicleViewModel) {
            vehicleViewModel.searchVehicles(searchText)
        }
    }

    function applyFilter() {
        if (vehicleViewModel) {
            vehicleViewModel.filterVehicles(filterStatus)
        }
    }

    function refreshVehicles() {
        if (vehicleViewModel) {
            vehicleViewModel.refreshVehicles()
        }
    }

    function syncSelectedAgv(agvNumber) {
        if (!vehicleViewModel || !vehicleViewModel.agvListModel || agvNumber === undefined || agvNumber === null) {
            selectedAgv = null
            selectedAgvIndex = -1
            return
        }

        const newIndex = vehicleViewModel.agvListModel.indexOfAgv(agvNumber)
        if (newIndex < 0) {
            selectedAgv = null
            selectedAgvIndex = -1
            return
        }

        selectedAgvIndex = newIndex
        selectedAgv = vehicleViewModel.agvListModel.getAgvData(newIndex)
    }

    function refreshSelectedAgv() {
        if (selectedAgv) {
            syncSelectedAgv(selectedAgv.agvNumber)
        }
    }

    function handleAgvDoubleClick(agv) {
        // 双击打开AGV详情对话框
        console.log("Open AGV details dialog for:", agv.id)
    }

    function handleAgvAction(action, agv) {
        switch(action) {
            case "enable":
                enableAgv(agv)
                break
            case "disable":
                disableAgv(agv)
                break
            case "charge":
                forceCharge(agv)
                break
            case "reset":
                resetAgv(agv)
                break
            default:
                console.log("Unknown AGV action:", action)
        }
    }

    function handleAgvModified(agv) {
        if (vehicleViewModel) {
            vehicleViewModel.updateVehicle(agv)
        }
    }

    function toggleMaintenanceMode(agv) {
        var newMode = !agv.maintenanceMode
        confirmDialog.title = newMode ? qsTr("进入维护模式") : qsTr("退出维护模式")
        confirmDialog.messageText = newMode
            ? qsTr("确定要将AGV %1 设置为维护模式吗？").arg(agv.id)
            : qsTr("确定要将AGV %1 退出维护模式吗？").arg(agv.id)
        confirmDialog.detailText = newMode ? qsTr("维护模式下AGV将不会接受新任务。") : ""
        confirmDialog.callback = function() {
            if (vehicleViewModel) {
                vehicleViewModel.setMaintenanceMode(agv.id, newMode)
            }
        }
        confirmDialog.open()
    }

    function enableAgv(agv) {
        if (vehicleViewModel) {
            vehicleViewModel.enableVehicle(agv.id)
        }
    }

    function disableAgv(agv) {
        confirmDialog.title = qsTr("禁用AGV")
        confirmDialog.messageText = qsTr("确定要禁用AGV %1 吗？").arg(agv.id)
        confirmDialog.detailText = qsTr("禁用后AGV将停止所有活动。")
        confirmDialog.callback = function() {
            if (vehicleViewModel) {
                vehicleViewModel.disableVehicle(agv.id)
            }
        }
        confirmDialog.open()
    }

    function forceCharge(agv) {
        const agvNumber = agv && agv.agvNumber !== undefined ? agv.agvNumber
                          : agv && agv.id !== undefined ? agv.id
                          : -1

        if (agvNumber === -1) {
            console.warn("VehicleManagementScreen: invalid AGV information for charge task")
            return
        }

        confirmDialog.title = qsTr("强制充电")
        confirmDialog.messageText = qsTr("确定要强制AGV %1 前往充电吗？").arg(agvNumber)
        confirmDialog.detailText = qsTr("当前任务可能会被中断。")
        confirmDialog.callback = function() {
            if (!taskViewModel) {
                console.warn("VehicleManagementScreen: TaskViewModel unavailable, unable to create charge task")
                return
            }

            const chainId = taskViewModel.createChargeTask(agvNumber)
            if (!chainId || chainId.length === 0) {
                console.warn("VehicleManagementScreen: failed to create charge task for AGV", agvNumber)
            }
        }
        confirmDialog.open()
    }

    function resetAgv(agv) {
        confirmDialog.title = qsTr("重置AGV")
        confirmDialog.messageText = qsTr("确定要重置AGV %1 吗？").arg(agv.id)
        confirmDialog.detailText = qsTr("这将清除AGV的当前状态和错误。")
        confirmDialog.callback = function() {
            if (vehicleViewModel) {
                vehicleViewModel.resetVehicle(agv.id)
            }
        }
        confirmDialog.open()
    }

    function executeManualControl(agv, commands) {
        if (vehicleViewModel) {
            vehicleViewModel.executeManualControl(agv.id, commands)
        }
    }

    function addNewAgv() {
        // TODO: 打开添加AGV对话框
        console.log("Add new AGV")
    }

    function showBatchOperations() {
        // TODO: 显示批量操作面板
        console.log("Show batch operations")
    }

    function openSystemSettings() {
        // TODO: 打开系统设置
        console.log("Open system settings")
    }

    function getVehicleStatusSummary() {
        if (!vehicleViewModel) {
            return qsTr("正在加载...")
        }

        var total = vehicleViewModel.totalAgvCount
        var online = vehicleViewModel.onlineAgvCount
        var idle = vehicleViewModel.idleAgvCount

        return qsTr("在线: %1/%2 | 空闲: %3")
            .arg(online).arg(total).arg(idle)
    }

    function getDetailedStatusText() {
        if (!vehicleViewModel) {
            return qsTr("正在加载...")
        }

        var total = vehicleViewModel.totalAgvCount
        var online = vehicleViewModel.onlineAgvCount
        var idle = vehicleViewModel.idleAgvCount

        return qsTr("总计: %1 | 在线: %2 | 空闲: %3")
            .arg(total).arg(online).arg(idle)
    }

    function formatCurrentTime() {
        return new Date().toLocaleTimeString()
    }

    // 状态颜色映射
    function getStatusColor(status) {
        switch(status) {
            case "idle":
                return Styles.Theme.success
            case "executing":
                return Styles.Theme.primary
            case "charging":
                return Styles.Theme.info
            case "error":
                return Styles.Theme.danger
            case "offline":
                return Styles.Theme.textTertiary
            default:
                return Styles.Theme.textSecondary
        }
    }

    // 状态文本映射
    function getStatusText(status) {
        switch(status) {
            case "idle":
                return qsTr("空闲")
            case "executing":
                return qsTr("执行中")
            case "charging":
                return qsTr("充电中")
            case "error":
                return qsTr("故障")
            case "offline":
                return qsTr("离线")
            default:
                return qsTr("未知")
        }
    }

    // 基于model数据的状态颜色
    function getStatusColorFromModel(isOnline, isCharging, isControlled) {
        if (!isOnline) return Styles.Theme.textTertiary
        if (isCharging) return Styles.Theme.info
        if (isControlled) return Styles.Theme.primary
        return Styles.Theme.success
    }

    // 基于model数据的状态文本
    function getStatusTextFromModel(isOnline, isCharging, isControlled) {
        if (!isOnline) return qsTr("离线")
        if (isCharging) return qsTr("充电中")
        if (isControlled) return qsTr("执行中")
        return qsTr("空闲")
    }
}
